package org.example.shejimoshi.create.danli;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

public class CompressUtils {
    public static byte[] compress(String str) throws IOException {
        byte[] data = str.getBytes(StandardCharsets.UTF_8);
        Deflater deflater = new Deflater();
        deflater.setLevel(Deflater.BEST_SPEED);
        deflater.setInput(data);
        deflater.finish();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
        try (DeflaterOutputStream dos = new DeflaterOutputStream(outputStream, deflater)) {
            byte[] buffer = new byte[1024];
            while (!deflater.finished()) {
                int count = deflater.deflate(buffer);
                dos.write(buffer, 0, count);
            }
        }
        return outputStream.toByteArray();
    }

    public static String decompress(byte[] data) throws IOException {
        Inflater inflater = new Inflater();
        inflater.setInput(data);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
        try (InflaterInputStream iis = new InflaterInputStream(new ByteArrayInputStream(data), inflater)) {
            byte[] buffer = new byte[1024];
            int count;
            while ((count = iis.read(buffer)) != -1) {
                outputStream.write(buffer, 0, count);
            }
        }
        return new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
    }
}
